package util;

import exception.CookieErrorException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @Author:石小俊
 * @Date:2022/12/13 14:47
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class CookieUtil {

    public static void addCookie(String name, String value, HttpServletResponse response){
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            throw new CookieErrorException("添加Cookie出错");
        }
    }

    public static void addCookie(String name, String value, int maxAge, HttpServletResponse response){
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            throw new CookieErrorException("添加Cookie出错");
        }
    }

    public static void removeCookie(String name,HttpServletResponse response){
        addCookie(name,"",0,response);
    }

    public static void modifyCookie(String name,String value,HttpServletResponse response){
        addCookie(name,value,response);
    }

    public static void modifyCookie(String name,String value,int maxAge, HttpServletResponse response){
        addCookie(name,value,maxAge,response);
    }

    public static String findByName(String name, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        try {
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(name)){
                        return URLDecoder.decode(cookie.getValue(),"UTF-8");
                    }
                }
            }
            return null;
        } catch (UnsupportedEncodingException e) {
            throw new CookieErrorException("Cookie出错");
        }
    }
}
